package com.itheima.userdemo.aop;

import com.itheima.userdemo.domain.Message;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Component("UserAspect")
@Aspect
public class UserAop {
        @Autowired
        private RabbitTemplate rabbitTemplate;
        private Message message;
        @Before("execution(* com.itheima.userdemo.controller.*.*(..))")
        public void before(JoinPoint joinPoint){
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = attributes.getRequest();
            message=new Message();
            message.setVisitTime(new Date());
            message.setMethodName(joinPoint.getSignature().getName());
            message.setPath(request.getRequestURL().toString());
        }
        @After("execution(* com.itheima.userdemo.controller.*.*(..))")
        public void after(){
            Date startTime = message.getVisitTime();
            Date endTime = new Date();
            message.setConsumerTime(endTime.getTime()-startTime.getTime());
            rabbitTemplate.convertAndSend("UserQueue",message);
            rabbitTemplate.convertAndSend("DelayExchange","delayMessage","延迟20秒，变成死信的消息来了");
        }
}
